/*
    Log管理器
*/

var LogManager = {
    logFilePath:"",
    id:0,
    sendLogList:[],
    debugLogList:[],
    outPutLogList:[],

    isOpenLog: false,
    MaxLogCount:0,

    Init:function(isDevelopment){},
    HookLogs:function(){},
    GetMsg:function(argList){},
    AddSysLog:function(argList, logType){},
    IsOpenLog:function(isOpenLog){},
    GetNowDateTimeStr:function(){},
    OutPutLog:function(){},
    SendLogToServer:function(){},
    GetLogMsgList:function(count){},
    ClearLogMsgList:function(){},
    GetDebugMsgList:function(count){},
};

/**
 * Area filter
 */
LogManager.Init = function(isDevelopment){

	LogManager.logFilePath = "";

	LogManager.id = 0;
    LogManager.debugLogList = [];
    LogManager.sendLogList = [];
	LogManager.outPutLogList = [];

	//默认开启,可以接收初始化阶段的log
	LogManager.isOpenLog = true;

	//超过多少条清除一半长度
	LogManager.MaxLogCount = 2000;

	LogManager.HookLogs();

    cc.log("create LogManager")
};

LogManager.HookLogs = function () {
    var self = this;

	cc.log('cc', function (...argList) {
		self.AddSysLog(argList, "log");
	}, 'log');

	// cc.log.hook('cc', function (...argList) {
 //        self.AddSysLog(argList, "info");
 //    }, 'info');

    cc.warn('cc', function (...argList) {              
        self.AddSysLog(argList, "warn"); 
    }, 'warn');

    cc.error('cc', function (...argList) {          
        self.AddSysLog(argList, "error"); 
    }, 'error');
};

//格式化 字典和列表为字符串
LogManager.GetMsg = function(argList){
    let count = argList.length;

    //转化字典和列表参数
    for(let index=1; index<count; index++){
        let value = argList[index];
        if(!value){
            continue
        }

        let valueType = Object.prototype.toString.call(value).slice("[object ".length, -1);

        if(valueType == "Array"){
            value = JSON.stringify(value);
        }
        else if(valueType == "Object"){
            value = JSON.stringify(value);
        }
        argList[index] = value;
    }
    return cc.js.formatStr.apply(null, argList);
},

LogManager.AddSysLog = function(argList, logType){
    if(LogManager.isOpenLog || logType=="error" || logType == "info"){

	    let msg = "";
	    try{
		    msg = this.GetMsg(argList);
		}
	    catch (error){
		    cc.error("error:%s", error.stack);
		    msg = "AddSysLog error";
	    }
	    LogManager.id += 1;
        LogManager.sendLogList.push([msg, logType, LogManager.id]);
        LogManager.outPutLogList.push([msg, logType, LogManager.id]);
	    LogManager.debugLogList.push([msg, logType, LogManager.id]);

	    if(LogManager.sendLogList.length >= LogManager.MaxLogCount){
		    LogManager.sendLogList = LogManager.sendLogList.slice(Math.floor(LogManager.MaxLogCount/2), LogManager.sendLogList.length);
	    }

	    if(LogManager.debugLogList.length >= LogManager.MaxLogCount){
		    LogManager.debugLogList = LogManager.debugLogList.slice(Math.floor(LogManager.MaxLogCount/2), LogManager.debugLogList.length);
	    }

	    if(LogManager.outPutLogList.length >= LogManager.MaxLogCount){
		    LogManager.outPutLogList = LogManager.outPutLogList.slice(Math.floor(LogManager.MaxLogCount/2), LogManager.outPutLogList.length);
	    }
    }
};

//是否开启发送LOG到log服务器
LogManager.IsOpenLog = function(isOpenLog){
    LogManager.isOpenLog = isOpenLog;
};

LogManager.GetNowDateTimeStr = function(){
	var dateStr = "";
	var myDate = new Date();
	var dataList = [myDate.getFullYear(), myDate.getMonth() + 1, myDate.getDate()];

    for (let index = 0; index < dataList.length; index++) {
		var value:any = dataList[index];
		if (value < 10){
			value = "0" + value;
		}
		if (index !== dataList.length - 1){

			dateStr += value + "-";
		}
		else{

			dateStr += value;
		}
	}
	return dateStr
};

//原生平台可以输出log文件
LogManager.OutPutLog = function(){

	if (!cc.sys.isNative){
		return
	}
	var timeStr = new Date().toLocaleString();

	var logText = "";
	for(var index=0,count=LogManager.outPutLogList.length-1; index<= count; index++){

		var logType = LogManager.outPutLogList[index][1];
		var logID = LogManager.outPutLogList[index][2];
		if(logType == "error"){
			logText += [timeStr, "\t[" + logID, "]\t###", LogManager.outPutLogList[index][0], "\n"].join("");
		}
		else{
			logText += [timeStr, "\t[" + logID, "]\t", LogManager.outPutLogList[index][0], "\n"].join("");
		}
	}

	if(!logText){
		return
	}

	LogManager.outPutLogList = [];

	var fileUtils = jsb.fileUtils;

	if(!LogManager.logFilePath){
		var clientPath = fileUtils.getWritablePath();
		if(!clientPath){
			return
		}
		//输出Log路径
		LogManager.logFilePath = clientPath + "Log/";
	}

	if(!fileUtils.isDirectoryExist(LogManager.logFilePath)){
		fileUtils.createDirectory(LogManager.logFilePath);
	}
	var logName = LogManager.GetNowDateTimeStr();
	//Log文件完整路径
	var logPathFileName= [LogManager.logFilePath, logName, ".txt"].join("");

	fileUtils.writeStringToFile(logText, logPathFileName);
};

//--------------回掉函数---------------


//发送log到服务器
LogManager.SendLogToServer = function(){
    //TODO:send log to server
    LogManager.sendLogList = [];
};

//截取多少条数据
LogManager.GetLogMsgList = function(count){
    if(!count){
        count = LogManager.sendLogList.length;
    }
    return LogManager.sendLogList.splice(0, count);
};

LogManager.ClearLogMsgList = function(){
    LogManager.sendLogList = [];
};

//debug层显示信息
LogManager.GetDebugMsgList = function(count){
	if(!count){
		count = LogManager.debugLogList.length;
	}
	return LogManager.debugLogList.splice(0, count);
}
